package org.bookie.web.pages.admin;

import org.apache.tapestry.IExternalPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.InjectObject;
import org.apache.tapestry.annotations.Persist;
import org.bookie.framework.CommonBasePage;
import org.bookie.model.Bet;
import org.bookie.model.Event;
import org.bookie.model.Role;
import org.bookie.model.security.Access;
import org.bookie.model.services.BetDAO;
import org.bookie.model.services.EventDAO;

@Access(role = Role.ADMIN)
public abstract class EditEvent extends CommonBasePage implements IExternalPage{
	public static final String EVENT_ID_PARAMETER = "eventId";

	public void activateExternalPage(Object[] parameters, IRequestCycle cycle) {
		if (parameters.length != 1) {
			throw new RuntimeException("Need one Long parameter event ID");
		}
		setEventId((Long) parameters[0]);
	}

	public void doSave() {
		setMessage(getMessages().getMessage("admin.edit.event.msg.updated"));
	}

	public void doRollback() {
		getEventDAO().rollbackTransaction();
	}

	/**
	 * Returns currently edited {@link Event}
	 * 
	 * @return
	 */
	public Event getEvent() {
		return getEventDAO().findById(getEventId());
	}

	/**
	 * Adds a new {@link Bet}
	 */
	public void doAddBet() {
		if (getDelegate().getHasErrors()) {
			return;
		}
		if (getEvent() != null) {
			Bet bet = new Bet(getBetLabel());
			getEvent().addBet(bet);
			setMessage(getMessages().getMessage(
					"admin.edit.event.msg.bet.added"));
		}
	}

	/**
	 * Injected {@link EventDAO} service.
	 * 
	 * @return instance of EventDAO
	 */
	@InjectObject("service:bookie.model.EventDAO")
	public abstract EventDAO getEventDAO();
	
	/**
	 * Injected {@link BetDAO} service.
	 * 
	 * @return instance of BetDAO
	 */
	@InjectObject("service:bookie.model.BetDAO")
	public abstract BetDAO getBetDAO();

	@Persist
	public abstract Long getEventId();

	public abstract void setEventId(Long value);

	public abstract String getBetLabel();
}
